from django.db import models
from django.contrib.auth.models import User
from django.utils.translation import ugettext as _
from siteupdate.settings import UPDATE_COMMAND, UPDATE_SHELL
import subprocess

class Update(models.Model):
    user = models.ForeignKey(User, verbose_name=_('User'), null=True, blank=True)
    updated_at = models.DateTimeField(_('Update executed'), auto_now_add=True)
    description = models.TextField(_('Update notes'), editable=True, help_text=_('Why are you updating this site?'))
    log = models.TextField(_('Update script output'), null=True, blank=True, help_text=_('All the output of the update script should be here'))
    
    def save(self, *args, **kwargs):
        update = bool(self.id)
        if not update and UPDATE_COMMAND:
            output = subprocess.Popen(UPDATE_COMMAND, executable=UPDATE_SHELL, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
            if output[1]:
                self.user.message_set.create(message=_('Update script returned a error, please check the logs!'))
                self.log = '%s: \n%s\n\n%s:\n%s' % (_('Output'), output[0], _('Errors'), output[1])
            else:
                self.user.message_set.create(message=_('Update script succesful executed'))
                self.log = output[0]

        return  models.Model.save(self, *args, **kwargs)

    def __unicode__(self):
        return self.description

    class Meta:
        ordering = ['-updated_at']
        verbose_name = _('Website update')
        verbose_name_plural = _('Website updates')
